<?php

namespace App\Http\Logic\Api;

use App\Models\AdminWechatUser;
use Exception;
use GuzzleHttp\Exception\GuzzleException;

class AuthLogic
{
    protected WechatAuth $wechatAuth;

    public function __construct(WechatAuth $wechatAuth)
    {
        $this->wechatAuth = $wechatAuth;
    }

    /**
     * @throws GuzzleException
     * @throws Exception
     */
    public function userPhone(string $code): array
    {
        try {
            return $this->wechatAuth->getUserPhone($code);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws GuzzleException
     * @throws Exception
     */
    public function login(string $code): array
    {
        try {
            $authData = $this->wechatAuth->login($code);
            if (empty($authData['openid'])) {
                throw new Exception('授权失败');
            }
//            $authData['openid'] = 'oaf156-jesHl4SE2hagB7tevBaH0';
            $member = AdminWechatUser::query()->where('open_id', $authData['openid'])->first();
            if (!empty($member)) {
                $data = $member->toArray();
            } else {
                $data = AdminWechatUser::query()->create(['open_id' => $authData['openid']])->toArray();
            }
            $data['token'] = AuditToken::getToken($data);

            return $data;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}
